<?php

// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2019 http://shopxo.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------

namespace app\service;

use think\Db;
use think\facade\Hook;
use app\service\ResourcesService;
use app\service\BrandService;
use app\service\RegionService;

/**
 * 商品服务层
 * @author   Devil
 * @blog     http://gong.gg/
 * @version  0.0.1
 * @datetime 2016-12-01T21:51:08+0800
 */
class BooksService {

    /**
     * 获取书单列表
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-08-29
     * @desc    description
     * @param   array           $params [输入参数: where, field, is_photo]
     */
    public static function BooksList($params = [], $flat = 0) {

        $where = empty($params['where']) ? [] : $params['where'];

        $order_by = empty($params['order_by']) ? 'id desc' : trim($params['order_by']);

        $m = isset($params['m']) ? intval($params['m']) : 0;
        $n = isset($params['n']) ? intval($params['n']) : 10;
        $data = Db::name('BooksList')->where($where)->order($order_by)->limit($m, $n)->select();

        return DataReturn('处理成功', 0, $data);
    }

    /**
     * 获取书单总数
     * @author   Devil
     * @blog    http://gong.gg/
     * @version 1.0.0
     * @date    2018-09-07
     * @desc    description
     * @param   [array]           $where [条件]
     */
    public static function BooksTotal($where = []) {
        return (int) Db::name('BooksList')->where($where)->count();
    }

    /**
     * 书单保存
     * @author   Devil
     * @blog     http://gong.gg/
     * @version  1.0.0
     * @datetime 2018-12-10T01:02:11+0800
     * @param    [array]          $params [输入参数]
     */
    public static function BooksSave($params = []) {

        // 请求参数
        $p = [
            [
                'checked_type' => 'length',
                'key_name' => 'title',
                'checked_data' => '2,60',
                'error_msg' => '书单名称格式 2~60 个字符',
            ],
            [
                'checked_type' => 'length',
                'key_name' => 'describe',
                'checked_data' => '160',
                'is_checked' => 1,
                'error_msg' => '书单主题描述 最多160个字符',
            ]
        ];
        $ret = ParamsChecked($params, $p);
        if ($ret !== true) {
            return DataReturn($ret, -1);
        }
        // 其它附件
        $data_fields = ['layout'];
        $attachment = ResourcesService::AttachmentParams($params, $data_fields);

        if ($attachment['code'] != 0) {
            return $attachment;
        }
        // 基础数据
        $data = [
             'title' => $params['title'],
             'is_recommended' => isset($params['is_recommended']) ? intval($params['is_recommended']) : 0,
             'describe' => empty($params['describe']) ? '' : $params['describe'],
             'layout'   => $attachment['data']['layout'],
        ];
        // 添加/编辑
        if (empty($params['id'])) {
            $data['add_time'] = time();
            $goods_id = Db::name('BooksList')->insertGetId($data);
        } else {
             $data['upd_time'] = time();
            if (Db::name('BooksList')->where(['id' => intval($params['id'])])->update($data)) {
                $goods_id = $params['id'];
            }
        }
     
        return DataReturn('操作成功', 0);
    }
    
    /**
     * 获取书单列表
     * @author   csb
     * @param   [int]           
     */
    public static function getBooksListBytype($user_id)
    {
        $data = Db::name('BooksList')->where(['user_id'=>$user_id])->select();
        return DataReturn('获取成功', 0, $data);
    }
    
     /**
     * 获取书籍所属的书单信息
     * @author   csb
     * @param   [int]           
     */
    public static function getGoodsByBooksList($goods_id,$field="*",$userid=0)
    {
        $data = Db::name('BooksGoods')->where(['goods_id'=>$goods_id,'userid'=>$userid])->field($field)->select();
        return DataReturn('获取成功', 0, $data);
    }
    
    
     /**
     * 获取书单书籍信息
     * @author   csb
     * @param   [int]           
     */
    public static function getBooksGoodsList($books_id)
    {
         $data = Db::name('BooksGoods')->alias('bg')->join(['__GOODS__' => 'g'], 'g.id=bg.goods_id')->join(['__BOOKS_LIST__' => 'bl'], 'bl.id=bg.books_id')->where(['books_id'=>$books_id])->field("bg.*,bl.title,g.images,g.title as goodsname")->select();
      //  $data = Db::name('BooksGoods')->where(['goods_id'=>$goods_id,'userid'=>$userid])->field($field)->select();
        return DataReturn('获取成功', 0, $data);
    }
 
    
    /**
     * 书单删除
  
     * @version  1.0.0
     * @datetime 2018-12-07T00:24:14+0800
     * @param    [array]          $params [输入参数]
     */
    public static function BooksListDelete($params = []) {
        // 参数是否有误
        if (empty($params['id'])) {
            return DataReturn('书单id有误', -1);
        }

        // 开启事务
        Db::startTrans();

        // 删除商品
        if (Db::name('BooksList')->delete(intval($params['id']))) {
            // 商品规格
            if (Db::name('BooksGoods')->where(['books_id' => intval($params['id'])])->delete() === false) {
                Db::rollback();
                return DataReturn('所属书籍删除失败', -100);
            }    
            // 提交事务
            Db::commit();
            return DataReturn('删除成功', 0);
        }

        Db::rollback();
        return DataReturn('删除失败', -100);
    }
    
    /**
     * 书单状态更新
    
     * @param    [array]          $params [输入参数]
     */
    public static function BooksStatusUpdate($params = []) {
        // 请求参数
        $p = [
            [
                'checked_type' => 'empty',
                'key_name' => 'id',
                'error_msg' => '操作id有误',
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'field',
                'error_msg' => '未指定操作字段',
            ],
            [
                'checked_type' => 'in',
                'key_name' => 'state',
                'checked_data' => [0, 1],
                'error_msg' => '状态有误',
            ],
        ];
        $ret = ParamsChecked($params, $p);
        if ($ret !== true) {
            return DataReturn($ret, -1);
        }

        // 数据更新
        if (Db::name('BooksList')->where(['id' => intval($params['id'])])->update([$params['field'] => intval($params['state']), 'upd_time' => time()])) {
            return DataReturn('操作成功');
        }
        return DataReturn('操作失败', -100);
    }

    /**
     * 批量添加书单书籍
     *    
     * @param    [array]       
     *    $params [输入参数]
     * // 请求参数
     */
    public static function addBookList($params = []) {
        
        $p = [
                [
                    'checked_type' => 'empty',
                    'key_name' => 'id',
                    'error_msg' => '书单id有误',
                ],
                [
                    'checked_type' => 'empty',
                    'key_name' => 'goods_ids',
                    'error_msg' => '书籍id有误',
                ]
        ];
        $ret = ParamsChecked($params, $p);
        if ($ret !== true) {
            return DataReturn($ret, -1);
        }
        
        $ids = explode(",", $params['goods_ids']);
        $data_list = [];
         
        $BooksGoods = Db("BooksGoods")->where(['books_id'=>$params['id']])->field('goods_id')->select();
        
        $time = time();
        foreach($ids as $v)
        {
            //判断书籍是否已经存在
            if(empty($BooksGoods)  ||  !in_array($v, array_column($BooksGoods, 'goods_id')))
            {
                    $data["books_id"] = $params['id'];
                    $data["goods_id"] = $v;
                    $data["add_time"] = $time;
                    $data_list[] = $data;
                    unset($data);
            }
          
        }
        
        // 数据添加
        if (Db::name('BooksGoods')->insertAll($data_list)) {
            return DataReturn('添加成功');
        }
        return DataReturn('添加失败', -100);
    }
}

?>